import { Op } from 'sequelize';
import <%= ClassName %> from '@/models/<%= moduleName %>/<%= businessName %>.model';
import { PaginationParams } from '@/types';
import { getLogger } from '@/utils/logger';

// 获取模块专用日志记录器
const logger = getLogger('<%= moduleName %>');

/**
 * <%= functionName %>服务类
 * 负责处理与<%= functionName %>相关的业务逻辑
 */
class <%= ClassName %>Service {
  /**
   * 查询<%= functionName %>列表
   * @param query 查询参数
   * @returns 返回<%= functionName %>列表Promise
   */
  public async select<%= ClassName %>List(query: any): Promise<<%= ClassName %>[]> {
    try {
      const where: any = this.buildQueryCondition(query);

      // 查询数据
      const <%= businessName %>List = await <%= ClassName %>.findAll({
        where,
        order: [['createTime', 'DESC']]
      });

      return <%= businessName %>List;
    } catch (error) {
      logger.error('查询<%= functionName %>列表失败', error);
      throw error;
    }
  }

  /**
   * 查询<%= functionName %>分页列表
   * @param query 分页查询参数
   * @returns 返回包含数据行和总数的对象
   */
  public async get<%= ClassName %>ListPaged(query: PaginationParams): Promise<{ rows: <%= ClassName %>[], count: number }> {
    try {
      const { pageNum = 1, pageSize = 10, ...filters } = query;
      const offset = pageNum && pageSize ? (pageNum - 1) * pageSize : undefined;
      const limit = pageSize ? Number(pageSize) : undefined;
      const where: any = this.buildQueryCondition(filters);

      // 如果pageSize为0，则不进行分页
      if (pageSize === 0) {
        const rows = await <%= ClassName %>.findAll({
          where,
          order: [['createTime', 'DESC']]
        });
        return { rows, count: rows.length };
      }

      // 查询数据（分页）
      const { rows, count } = await <%= ClassName %>.findAndCountAll({
        where,
        order: [['createTime', 'DESC']],
        offset,
        limit
      });

      return { rows, count };
    } catch (error) {
      logger.error('查询<%= functionName %>分页列表失败', error);
      throw error;
    }
  }

  /**
   * 构建查询条件
   * @param params 查询参数
   * @returns 查询条件对象
   * @private
   */
  private buildQueryCondition(params: any): any {
    const where: any = {};

    // 构建查询条件
<% columns.forEach(function(column) { %>
<% if(column.isQuery === '1') { %>
    if (params.<%= column.javaField %>) {
<% if(column.queryType === 'EQ') { %>
      where.<%= column.javaField %> = params.<%= column.javaField %>;
<% } else if(column.queryType === 'NE') { %>
      where.<%= column.javaField %> = { [Op.ne]: params.<%= column.javaField %> };
<% } else if(column.queryType === 'GT') { %>
      where.<%= column.javaField %> = { [Op.gt]: params.<%= column.javaField %> };
<% } else if(column.queryType === 'GTE') { %>
      where.<%= column.javaField %> = { [Op.gte]: params.<%= column.javaField %> };
<% } else if(column.queryType === 'LT') { %>
      where.<%= column.javaField %> = { [Op.lt]: params.<%= column.javaField %> };
<% } else if(column.queryType === 'LTE') { %>
      where.<%= column.javaField %> = { [Op.lte]: params.<%= column.javaField %> };
<% } else if(column.queryType === 'LIKE') { %>
      where.<%= column.javaField %> = { [Op.like]: `%${params.<%= column.javaField %>}%` };
<% } else if(column.queryType === 'BETWEEN') { %>
      if (params.<%= column.javaField %>Start && params.<%= column.javaField %>End) {
        where.<%= column.javaField %> = { [Op.between]: [params.<%= column.javaField %>Start, params.<%= column.javaField %>End] };
      }
<% } %>
    }
<% } %>
<% }); %>

    return where;
  }

  /**
   * 查询<%= functionName %>详细信息
   * @param <%= pkColumn.javaField %> <%= functionName %>ID
   * @returns 返回<%= functionName %>详细信息
   */
  public async select<%= ClassName %>ById(<%= pkColumn.javaField %>: <%= pkColumn.getTypeScriptType() %>): Promise<<%= ClassName %> | null> {
    try {
      return await <%= ClassName %>.findByPk(<%= pkColumn.javaField %>);
    } catch (error) {
      logger.error(`查询<%= functionName %>详细信息失败，ID: ${<%= pkColumn.javaField %>}`, error);
      throw error;
    }
  }

  /**
   * 新增<%= functionName %>
   * @param <%= businessName %> <%= functionName %>信息
   * @returns 返回创建的<%= functionName %>对象
   */
  public async insert<%= ClassName %>(<%= businessName %>: any): Promise<<%= ClassName %>> {
    try {
      return await <%= ClassName %>.create(<%= businessName %>);
    } catch (error) {
      logger.error('新增<%= functionName %>失败', error);
      throw error;
    }
  }

  /**
   * 修改<%= functionName %>
   * @param <%= businessName %> <%= functionName %>信息
   * @returns 返回影响的行数
   */
  public async update<%= ClassName %>(<%= businessName %>: any): Promise<number> {
    try {
      const [affectedCount] = await <%= ClassName %>.update(<%= businessName %>, {
        where: { <%= pkColumn.javaField %>: <%= businessName %>.<%= pkColumn.javaField %> }
      });
      return affectedCount;
    } catch (error) {
      logger.error(`修改<%= functionName %>失败，ID: ${<%= businessName %>.<%= pkColumn.javaField %>}`, error);
      throw error;
    }
  }

  /**
   * 批量删除<%= functionName %>
   * @param <%= pkColumn.javaField %>s 需要删除的<%= functionName %>ID数组
   * @returns 返回删除的行数
   */
  public async delete<%= ClassName %>ByIds(<%= pkColumn.javaField %>s: <%= pkColumn.getTypeScriptType() %>[]): Promise<number> {
    try {
      logger.info(`批量删除<%= functionName %>，ID列表: ${<%= pkColumn.javaField %>s.join(', ')}`);
      return await <%= ClassName %>.destroy({
        where: { <%= pkColumn.javaField %>: { [Op.in]: <%= pkColumn.javaField %>s } }
      });
    } catch (error) {
      logger.error(`批量删除<%= functionName %>失败，ID列表: ${<%= pkColumn.javaField %>s.join(', ')}`, error);
      throw error;
    }
  }

  /**
   * 删除<%= functionName %>信息
   * @param <%= pkColumn.javaField %> <%= functionName %>ID
   * @returns 返回删除的行数
   */
  public async delete<%= ClassName %>ById(<%= pkColumn.javaField %>: <%= pkColumn.getTypeScriptType() %>): Promise<number> {
    try {
      logger.info(`删除<%= functionName %>，ID: ${<%= pkColumn.javaField %>}`);
      return await <%= ClassName %>.destroy({
        where: { <%= pkColumn.javaField %> }
      });
    } catch (error) {
      logger.error(`删除<%= functionName %>失败，ID: ${<%= pkColumn.javaField %>}`, error);
      throw error;
    }
  }
}

export default new <%= ClassName %>Service(); 